#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fstream>

#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"

#include "ImageReader.h"
#include "FingerRootsDetector.h"

using namespace cv;
using namespace std;

int main(int args, char **argv)
{
    int *figCon = new int[6];
    const string img_load_base_color = argv[1]; //"/home/yjy/dataset/palmprint_dectection/palmprint/";
    const string img_load_base_gray = argv[2];  //"/home/yjy/dataset/palmprint_dectection/palmvein/";
    const string fincon_save_base = argv[3];    //"/home/yjy/dataset/palmprint_dectection/output/";
    string file_name_color;
    string file_name_gray;
    int length, flag;
    Mat gray_img;
    FingerRootsDetector *fd;
    dirent *filename;
    DIR *dir = opendir(img_load_base_color.c_str());
    ofstream txt(fincon_save_base + "figCon.txt");
    char *buff = new char[100];

    while ((filename = readdir(dir)) != NULL)
    {
        if (strcmp(filename->d_name, ".") == 0 ||
            strcmp(filename->d_name, "..") == 0)
            continue;

        file_name_color = filename->d_name;
        length = file_name_color.length();
        file_name_gray = file_name_color.substr(0, length); //length - 11

        //detect & return finger roots [x1,y1,x2,y2,x3,y3]
        ImageReader ir(img_load_base_gray + file_name_gray);
        // ImageReader ir_gray(img_load_base_gray + file_name_gray);
        fd = new FingerRootsDetector(ir);
        fd->detect();
        flag = fd->getDetectedArr(figCon);
        if (flag == 0)
        {
            buff[0] = 0;
            buff[1] = 0;
            buff[2] = 0;
            buff[3] = 0;
            buff[4] = 0;
            buff[5] = 0;
        }
        // adjust coordinates according to device distance
        // figCon[0] += 28;
        // figCon[2] += 28;
        // figCon[4] += 28;

        gray_img = fd->getResult();

        //save mask
        cv::imwrite(fincon_save_base + file_name_color, gray_img);

        //write figCon to txt
        sprintf(buff, "%s %d %d %d %d %d %d\n", file_name_color.c_str(), figCon[0], figCon[1], figCon[2], figCon[3], figCon[4], figCon[5]);
        txt << buff;

        gray_img.release();
        delete fd;
    }

    txt.close();
    delete buff;
    delete filename;
    delete figCon;

    return 0;
}
